//
//  MainViewController.m
//  bluetooth
//
//  Created by 周季阳 on 15/6/17.
//  Copyright (c) 2015年 switch. All rights reserved.
//

#import "MainViewController.h"
#import "UIViewAdditions.h"
#import "ScanSuccessController.h"
#import <CoreMotion/CoreMotion.h>
#import "LZAudioTool.h"
#import "OLImage.h"
#import "OLImageView.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "AppDelegate.h"
#import "BluetoothLibary.h"
#import "ActionViewController.h"
#import "ShopViewController.h"
#import "AftermarketViewController.h"
#import "PersonViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
@interface MainViewController ()<BluetoothDelegate>
{
    NSTimer *AutoTimer;
    CMMotionManager *_manager;
    NSTimer *zTimer;
    UILabel *label;
    UIImageView * imgView;
    UIButton *leftBtn;
    UIButton *rightBtn;
    UIImageView *image;
    OLImageView *Aimv;
    UIButton *cukBtn;
    UIButton *lookupBtn;
}
@property (nonatomic, assign)BOOL zIsEnd;//判断是否摇一摇结束
@property (strong, nonatomic) CBCentralManager      *centralManager;
@property (strong, nonatomic) CBPeripheral          *discoveredPeripheral;
@property (nonatomic, strong) BluetoothLibary *bluetoothClient;
@end

@implementation MainViewController
@synthesize zIsEnd,zArray,zArrayBlue;
static int i = 0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        [self createrView];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    //1.0/60.0
    //AutoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(autoChange) userInfo:nil repeats:YES];
    if (_bluetoothClient == nil)
    {
        self.bluetoothClient = [[BluetoothLibary alloc] init];
        self.bluetoothClient.delegate = self;
    }
    if (zArray == nil) {
        zArray = [[NSMutableArray alloc]init];
    }
    if (zArrayBlue == nil) {
        zArrayBlue = [[NSMutableArray alloc]init];
    }
}
//- (BluetoothLibary *)bluetoothClient
//{
//   
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden=YES;
    [self.view setBackgroundColor:[self colorWithHexString:@"#F5F5F5"]];
    // Do any additional setup after loading the view.
    //监听是否下个界面摇一摇
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(clickXia) name:@"jianting" object:nil];
    
    // 初始化蓝牙通讯模块
    self.bluetoothClient = [[BluetoothLibary alloc] init];
    self.bluetoothClient.delegate = self;
    
    _manager = [[CMMotionManager alloc]init];
    
    _manager.accelerometerUpdateInterval=1.0/60.0;
    
    [_manager startAccelerometerUpdates];
    zIsEnd = YES;
    
    //_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
   


    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    appDelegate.isWhere = @"1";
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cleanUpBlue) name:@"cleanUp" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chushihua) name:@"chushihua" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tiaozhuan) name:@"tiaozhuan" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tiaozhuan1) name:@"tiaozhuan1" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tiaozhuan2) name:@"tiaozhuan2" object:nil];
}
-(void)chushihua{
    [self clickLookupBtn];
}
-(void)cleanUpBlue{
    //关闭通知并断开连接
        if (_discoveredPeripheral != nil) {
            for (CBService *service in _discoveredPeripheral.services) {
                if (service.characteristics != nil) {
                    for (CBCharacteristic *characteristic in service.characteristics) {
                        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_NOTIFY_UUID]]) {
                            if (characteristic.isNotifying) {
                                [_discoveredPeripheral setNotifyValue:NO forCharacteristic:characteristic];
                                [self performSelector:@selector(delNotification:) withObject:@"name" afterDelay:0.5f];
                                return;
                            }
                        }
                    }
                }
            }
        }
        //
        //disconnect peripheral
        [self.centralManager cancelPeripheralConnection:self.discoveredPeripheral];

}
-(void)delNotification:(NSString*)name{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"clickend" object:nil];
}
#pragma mark - 蓝牙初始化回调
/** centralManagerDidUpdateState is a required protocol method.
 *  Usually, you'd check for other states to make sure the current device supports LE, is powered on, etc.
 *  In this instance, we're just using it to wait for CBCentralManagerStatePoweredOn, which indicates
 *  the Central is ready to be used.
 */
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    if (central.state != CBCentralManagerStatePoweredOn) {
        // In a real app, you'd deal with all the states correctly
        return;
    }
    
    // The state must be CBCentralManagerStatePoweredOn...
    
    // ... so start scanning
   
    
}


/** Scan for peripherals - specifically for our service's 128bit CBUUID
 */
- (void)scan
{
    i = 0;
    //[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]
                                                //options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
   // NSLog(@"Scanning started");

    [self.bluetoothClient startScan:nil isReset:YES timeoutSeconds:0];

}
- (void)didDiscoverPeripheral:(CBPeripheral *)peripheral
{
    self.discoveredPeripheral = peripheral;
    
    if ([[peripheral.identifier UUIDString] isEqualToString:@"A5EB7516-1A9C-874A-B152-BF9ACE7F4AD3"]) {
        [zArray addObject:@"C-UK面膜机"];
        [zArrayBlue addObject:peripheral];
    }else{
        [zArray addObject:@"SuperQ"];
        [zArrayBlue addObject:peripheral];
    }
    
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(todoSomething1) object:nil];
    [self performSelector:@selector(todoSomething1) withObject:nil afterDelay:1.0f];
    
}
-(void)todoSomething1{
    [self pree];
    
    ScanSuccessController *scusse= [[ScanSuccessController alloc]init];
    scusse.zArrayData = zArray;
    scusse.zArrayBlue = zArrayBlue;
    scusse.discoveredPeripheral = self.discoveredPeripheral;
    scusse.centralManager = self.centralManager;
    scusse.bluetoothClient = self.bluetoothClient;
    _bluetoothClient = nil;
    zArray = nil;
    zArrayBlue = nil;
    [self.navigationController pushViewController:scusse animated:YES];

    //[self performSelector:@selector(yanhou) withObject:self afterDelay:3.0];
}
-(void)yanhou{
    //if ([zArray count] == 2) {
       //}
}
#pragma mark - 左抽屉跳转到分页
-(void)tiaozhuan{
    AftermarketViewController *deblocking = [[AftermarketViewController alloc]init];
    [self.navigationController pushViewController:deblocking animated:YES];
}
#pragma mark - 左抽屉跳转到商城
-(void)tiaozhuan1{
    ShopViewController *shop = [[ShopViewController alloc]init];
    [self.navigationController pushViewController:shop animated:YES];
}
#pragma mark - 左抽屉跳转到个人中心
-(void)tiaozhuan2{
    PersonViewController *person = [[PersonViewController alloc]init];
    [self.navigationController pushViewController:person animated:YES];
}
#pragma mark - 扫描周围
/** This callback comes whenever a peripheral that is advertising the TRANSFER_SERVICE_UUID is discovered.
 *  We check the RSSI, to make sure it's close enough that we're interested in it, and if it is,
 *  we start the connection process
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    // Reject any where the value is above reasonable range
    //    if (RSSI.integerValue > -15) {
    //        return;
    //    }
    //
    //    // Reject if the signal strength is too low to be close enopough (Close is around -22dB)
    //    if (RSSI.integerValue < -35) {
    //        return;
    //    }
    
    NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);
    
    // Ok, it's in range - have we already seen it?
    if (self.discoveredPeripheral != peripheral) {
        [self pree];
         self.discoveredPeripheral = peripheral;
        [zArray addObject:peripheral.name];
        //[zArray addObject:@"C-UK面膜机"];
        ScanSuccessController *scusse= [[ScanSuccessController alloc]init];
        scusse.zArrayData = zArray;
        scusse.discoveredPeripheral = peripheral;
        scusse.centralManager = self.centralManager;
        [self.navigationController pushViewController:scusse animated:YES];
        // Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it
       
        
        // And connect
        NSLog(@"Connecting to peripheral %@", peripheral);
        //[self.centralManager connectPeripheral:peripheral options:nil];
    }
}


/** If the connection fails for whatever reason, we need to deal with it.
 */
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Failed to connect to %@. (%@)", peripheral, [error localizedDescription]);
    //[self cleanup];
}

#pragma mark - 下个界面回调
-(void)clickXia{
    [self scan];
    label.text = @"搜索中";
    [LZAudioTool playMusic:@"5018.mp3"];
    zIsEnd = NO;
    NSLog(@"motionBegan");
    //zTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(pree) userInfo:nil repeats:NO];
    //sleep(0.2);
}
#pragma mark - 定时器事件
-(void)autoChange

{
   //NSLog(@"%.2f --%.2f --%.2f",_manager.accelerometerData.acceleration.x,_manager.accelerometerData.acceleration.y,_manager.accelerometerData.acceleration.z);
    //根据自己需求调节x y z
    
    if (fabs(_manager.accelerometerData.acceleration.x) > 1.6 || fabs(_manager.accelerometerData.acceleration.y) > 1.8 || fabs(_manager.accelerometerData.acceleration.z) > 2.1)
        
    {
        
        NSLog(@"我晃动了 。。。。。");
        if (zIsEnd == NO) {
            
        }else{
            //重新构建UI
            [self initUII];
            
             //_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
            //扫描蓝牙
             [self scan];
            
            
            label.text = @"搜索中";
            [LZAudioTool playMusic:@"5018.mp3"];
            zIsEnd = NO;
            NSLog(@"motionBegan");
            
            //CGFloat offset = self.bg.height/6;
            CGFloat duration = 0.2;
            
            //    [UIView animateWithDuration:duration animations:^{
            //            self.up.y -= offset;
            //            self.down.y += offset;
            //    }];
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:duration];
                [UIView setAnimationDelegate:self];
               
                [UIView commitAnimations];
            });
//            zTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(pree) userInfo:nil repeats:NO];
//            sleep(0.2);
            
        }
        
    }
    
}
#pragma mark - 摇一摇结束
-(void)pree{
    if (zIsEnd== NO) {
        [LZAudioTool playMusic:@"5012.wav"];
        zIsEnd = YES;
        label.text = @"点击进行搜索";
        [self lateTo];
    }
}
-(void)lateTo{
    //ScanSuccessController *scan = [[ScanSuccessController alloc]init];
    //[self presentViewController:scan animated:YES completion:nil];
    [leftBtn removeFromSuperview];
    leftBtn = nil;
    [rightBtn removeFromSuperview];
    rightBtn = nil;
    [label removeFromSuperview];
    label = nil;
    [Aimv removeFromSuperview];
    Aimv = nil;
    [self createrView];
    //[self.navigationController pushViewController:scan animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createrView{
    imgView = [[UIImageView alloc]init];
    [imgView setFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:imgView];
    imgView.userInteractionEnabled = YES;
    
    [self initNav];
    self.view.backgroundColor = [self colorWithHexString:@"#F1F1F1"];
    
    navTitle.text = @"个人中心";
    [navRightBtn setTitle:@"更换账号" forState:UIControlStateNormal];
    navRightBtn.frame = CGRectMake(SCREEN_WIDTH-74 , 20, 64, SCREEN_WIDTH*0.2-20);
    navRightBtn.hidden = NO;
    
    [navBtn setImage:[UIImage imageNamed:@"制作完成_03"] forState:UIControlStateNormal];
    navBtn.frame = CGRectMake(10, 30, 63, 21);
    
    
    cukBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cukBtn setBackgroundImage:[UIImage imageNamed:@"查找设备_03"] forState:UIControlStateNormal];
    cukBtn.frame = CGRectMake((SCREEN_WIDTH-120)/2, navView.bottom+150, 120, 122);
    //[cukBtn addTarget:self action:@selector(clickScan) forControlEvents:UIControlEventTouchUpInside];
    [imgView addSubview:cukBtn];
    
//    label = [[UILabel alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-100, SCREEN_WIDTH, 20)];
//    label.text = @"点击进行搜索";
//    label.font = [UIFont systemFontOfSize:15];
//    label.textAlignment = NSTextAlignmentCenter;
//    label.backgroundColor = [UIColor clearColor];
//    label.textColor = [UIColor whiteColor];
//    [imgView addSubview:label];
    
    lookupBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lookupBtn.frame = CGRectMake((SCREEN_WIDTH-285)/2, cukBtn.bottom+100, 285, 38);
    [lookupBtn setBackgroundImage:[UIImage imageNamed:@"首页_06"] forState:UIControlStateNormal];
    [lookupBtn addTarget:self action:@selector(clickLookupBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:lookupBtn];
}
#pragma mark - 点击扫描
-(void)clickLookupBtn{
    //重新构建UI
    [self initUII];
    
    //_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //扫描蓝牙
    [self scan];
    
    
    lookupBtn.hidden = YES;
    [LZAudioTool playMusic:@"5018.mp3"];
    zIsEnd = NO;
    NSLog(@"motionBegan");

}

#pragma mark - 重新构建UI
-(void)initUII{
    [leftBtn removeFromSuperview];
    leftBtn = nil;
    [rightBtn removeFromSuperview];
    rightBtn = nil;
    [label removeFromSuperview];
    label = nil;
    
    Aimv = [OLImageView new];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"查找设备gif(1)" ofType:@"gif"];
    NSData *GIFDATA = [NSData dataWithContentsOfFile:filePath];
    Aimv.image = [OLImage imageWithData:GIFDATA];
    Aimv.userInteractionEnabled = YES;
    [Aimv setFrame:[UIScreen mainScreen].bounds];
    
    [self.view addSubview:Aimv];
    
    [self initNav];
    self.view.backgroundColor = [self colorWithHexString:@"#F5F5F5"];
    
    navTitle.text = @"个人中心";
    [navRightBtn setTitle:@"更换账号" forState:UIControlStateNormal];
    navRightBtn.frame = CGRectMake(SCREEN_WIDTH-74 , 20, 64, SCREEN_WIDTH*0.2-20);
    navRightBtn.hidden = NO;
    
    [navBtn setImage:[UIImage imageNamed:@"制作完成_03"] forState:UIControlStateNormal];
    navBtn.frame = CGRectMake(10, 30, 63, 21);
    
    image = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-120)/2, navView.bottom+150, 120, 122)];
    [image setImage:[UIImage imageNamed:@"查找设备_03"]];
    [Aimv addSubview:image];
    
    label = [[UILabel alloc]initWithFrame:CGRectMake(0, image.bottom+5, SCREEN_WIDTH, 20)];
    label.text = @"正在搜索...";
    label.font = [UIFont boldSystemFontOfSize:12];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [self colorWithHexString:@"#D45556"];
    [Aimv addSubview:label];


}
#pragma mark - 更换账号
-(void)clickRightBtn{
    //暂时
//    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    // 在delegate中初始化新的controller
//    //[delegate initTabbarController];
//    // 修改rootViewController
//    LoginViewController *mainVC = [LoginViewController new];
//    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:mainVC];
//    
//    [delegate.window addSubview:nav1.view];
//    [self.view removeFromSuperview];
//    delegate.window.rootViewController = nav1;
    
    ScanSuccessController *scan = [[ScanSuccessController alloc]init];
    [self.navigationController pushViewController:scan animated:YES];
    
    
}
#pragma mark - 点击菜单
-(void)clickBackBtn{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"clickLeft" object:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
    [AutoTimer invalidate];
    AutoTimer = nil;
    [zTimer invalidate];
    AutoTimer = nil;
}

//#pragma mark - 扫描二维码
//-(void)clickRightBtn{
//    ScanSuccessController *scusse= [[ScanSuccessController alloc]init];
//    [self.navigationController pushViewController:scusse animated:YES];
//
//}
@end
